/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 *
 * @format
 */

import React, { useRef, useState, useEffect, Component } from 'react'
import type { PropsWithChildren } from 'react'
import { useisScroll, ScrollProvider } from './src/contexts/scrollContext'
import {
  SafeAreaView,
  ScrollView,
  StatusBar,
  StyleSheet,
  Text,
  useColorScheme,
  View,
  PixelRatio
} from 'react-native'
import { WebView } from 'react-native-webview'

import {
  Colors,
  DebugInstructions,
  Header,
  LearnMoreLinks,
  ReloadInstructions
} from 'react-native/Libraries/NewAppScreen'

import Divide from './src/commonComponents/divide'

import MyFlex43 from './src/components/4_3MyFlex'
import ClassView65 from './src/components/6_5ClassView'
import FunctionView66 from './src/components/6_6FunctionView/index'
import TimerPractise69 from './src/components/6_9zuoye_rnCalculate'
import ViewDemo72 from './src/components/7_2ViewDemo'
import TextDemo73 from './src/components/7_3TextDemo'
import ImageDemo74 from './src/components/7_4ImageDemo'
import ImageBackgroundDemo7_5 from './src/components/7_5ImageBackgroundDemo'
import TextInputDemo7_6 from './src/components/7_6TextInputDemo'
import TouchableOpacityDemo7_7 from './src/components/7_7TouchableOpacityDemo'
import TouchableHighlightDemo7_8 from './src/components/7_8TouchableHighlightDemo_TouchableWithoutFeedback'
import ButtonDemo7_10 from './src/components/7_10ButtonDemo'
import PressableDemo7_11 from './src/components/7_11PressableDemo'
import ScrollViewDemo7_12 from './src/components/7_12ScrollViewDemo'
import FlatListDemo7_13 from './src/components/7_13FlatListDemo'
import SectionList7_14 from './src/components/7_14SectionList_RefreshControl_statusBar'
import ModalDemo7_16 from './src/components/7_16ModalDemo'
import Switch7_18 from './src/components/7_18Switch'
import PersonalInfo7_19 from './src/components/7_19zuoye_PersonalInfo'
import Alert_console_platform_linking_PixelRatio_BackHandler_PermissionsAndroid82_89 from './src/components/8_2Alert_console_platform_linking_PixelRatio_BackHandler_PermissionsAndroid'
import Vibration_ToastAndroid_Transform_Keyboard8_10 from './src/components/8_10Vibration震动交互_ToastAndroid安卓平台的提示_Transform矩阵变换_Keyboard'

import Animate_index_9 from './src/components/9_animate动画/9_animate_index'
import 跟随动画延迟难题9_10 from './src/components/9_animate动画/9_10跟随动画延迟难题Event'
import 自定义Modal背景动画910_from_ModalDemo7_16 from './src/components/9_animate动画/9_10自定义Modal背景动画'
import Context实例演示12_2 from './src/components/12_2Context上下文/RootView'
// --------ts
import Typescript11 from './src/components/11_typescript/index'

import MemoAndUsememo from './src/components/14_memo与性能优化'
import ConsumeList14_2 from '@/components/14_memo与性能优化/14_2useMemo缓存计算结果_缓存ui_useCallback_ConsumeList' // 在app.jsx里
import RefDemo from '@/components/15_ref转发'
import CommunicateWithNative from '@/components/16_(桥接原生)精通4种桥接方式'

type SectionProps = PropsWithChildren<{
  title: string
}>

function Section({ children, title }: SectionProps): JSX.Element {
  const isDarkMode = useColorScheme() === 'dark'
  return (
    <View style={styles.sectionContainer}>
      <Text
        style={[
          styles.sectionTitle,
          {
            color: isDarkMode ? Colors.white : Colors.black
          },
        ]}>
        {title}
      </Text>
      <Text
        style={[
          styles.sectionDescription,
          {
            color: isDarkMode ? Colors.light : Colors.dark
          },
        ]}>
        {children}
      </Text>
    </View>
  )
}

function App(): JSX.Element {
  const isDarkMode = useColorScheme() === 'dark'

  const backgroundStyle = {
    backgroundColor: isDarkMode ? Colors.darker : Colors.lighter
  };

  const [ScrollObj, setScrollObj] = useState({ x: 0, y: 0 })
  const scrollView = useRef<ScrollView>(null)

  //https://react.docschina.org/reference/react/useEffect
  useEffect(() => {
    let timer = setTimeout(() => {
      setScrollObj((oldValue) => {
        console.log('app.tsx_oldValue_keys: ' + Object.keys(oldValue))
        console.log('app.tsx_oldValue: ' + oldValue.x + ' ' + oldValue.y)
        const scrollToObj = { x: 0, y: 200 }
        if (scrollView.current != null) {
          // console.log(scrollView.current);

          const scrollToEnd = scrollView.current!.scrollToEnd as Function
          scrollToEnd({ animated: true })
        }
        return scrollToObj
      })
    }, 2000)

    return () => {
      console.log(`将组件挂载到页面时，将运行 setup 代码。
  重新渲染 依赖项 变更的组件后：
  首先，使用旧的 props 和 state 运行 cleanup 代码。
  然后，使用新的 props 和 state 运行 setup 代码。
  当组件从页面卸载后，cleanup 代码 将运行最后一次。
  useEffect的清理函数（即return的函数）会在两种情况下执行：
1. 组件卸载（unmount）时：这是为了清理那些在组件存在期间持续存在的副作用，比如定时器、订阅等。
2. 组件重新渲染（re-render）时：在每次重新渲染之前，清理函数会被调用，以清理上一次副作用的影响。然后，useEffect中的主体函数会执行，可能会创建新的副作用。
  `)
      clearTimeout(timer)
    }
  }, [])

  // 是否在滚动的部分代码
  const { isScroll, dispatch } = useisScroll()
  const handleScroll = (event: {
    nativeEvent: {
      contentOffset: { y: any }
      layoutMeasurement: { height: any }
      contentSize: { height: any }
    }
  }) => {
    // console.log('--------------scroll--------------');
    const y = event.nativeEvent.contentOffset.y // 这是滚动视图的垂直滚动偏移量。当滚动视图滚动时，这个值会改变。如果滚动视图滚动到顶部，这个值为0；如果滚动视图滚动到底部，这个值等于滚动视图内容的高度减去滚动视图的高度。
    const height = event.nativeEvent.layoutMeasurement.height //这是滚动视图的高度。这个值在滚动视图的大小改变时会更新，例如当设备的方向改变时。这个值不包括滚动视图的padding。
    const contentHeight = event.nativeEvent.contentSize.height // 表示滚动视图的内容到达的最底部的位置，如果这个值等于或大于滚动视图内容的总高度（`event.nativeEvent.contentSize.height`），那么就表示滚动视图已经滚动到底部。
    if (
      PixelRatio.roundToNearestPixel(y + height) >=
      PixelRatio.roundToNearestPixel(contentHeight)
    ) {
      console.log('---------已经滚动到底部------------')
      // 在这里执行你的操作
      return dispatch({ type: 'false' })
    }
    dispatch({ type: 'true' })
  }
  const handleScrollEnd = () => {
    dispatch({ type: 'false' })
  }
  return (
    <SafeAreaView style={backgroundStyle}>
      <StatusBar
        barStyle={isDarkMode ? 'light-content' : 'dark-content'}
        backgroundColor={backgroundStyle.backgroundColor}
      />
      {/* <ScrollView
        contentInsetAdjustmentBehavior="automatic"
        style={backgroundStyle}>
        <Header />
        <View
          style={{
            backgroundColor: isDarkMode ? Colors.black : Colors.white,
          }}>
          <Section title="Step One">
            Edit <Text style={styles.highlight}>App.tsx</Text> to change this
            screen and then come back to see your edits.
          </Section>
          <Section title="See Your Changes">
            <ReloadInstructions />
          </Section>
          <Section title="Debug">
            <DebugInstructions />
          </Section>
          <Section title="Learn More">
            Read the docs to discover what to do next:
          </Section>
          <LearnMoreLinks />
        </View>
      </ScrollView>*/}
      <ScrollView
        contentInsetAdjustmentBehavior="automatic"
        scrollEventThrottle={16}
        onScroll={handleScroll}
        onMomentumScrollEnd={handleScrollEnd}
        ref={scrollView}
        style={backgroundStyle}>
        <MyFlex43 />

        <Divide isBig />
        <ClassView65 name="lisi" age={90} isManry={false} />

        <Divide isBig />
        <FunctionView66 />

        <Divide isBig />
        <TimerPractise69 />

        <Divide isBig />
        <ViewDemo72 />

        <Divide isBig />
        <TextDemo73 />

        <Divide isBig />
        <ImageDemo74 />

        <Divide isBig />
        <ImageBackgroundDemo7_5 />

        <Divide isBig />
        <TextInputDemo7_6 />

        <Divide isBig />
        <TouchableOpacityDemo7_7 />

        <Divide isBig />
        <TouchableHighlightDemo7_8 />

        <Divide isBig />
        <ButtonDemo7_10 />

        <Divide isBig />
        <PressableDemo7_11 />

        <Divide isBig />
        <Switch7_18 />

        <Divide isBig />
        <Alert_console_platform_linking_PixelRatio_BackHandler_PermissionsAndroid82_89 />

        <Divide isBig />
        <Vibration_ToastAndroid_Transform_Keyboard8_10 />

        <Animate_index_9 />

        <Divide isBig />
        <Typescript11 />

        {/*<Divide isBig />
         <View style={{position: 'relative'}}>
          <Context实例演示12_2 />
        </View> */}
        {/**/}
        <Divide isBig />
        <View style={{ position: 'relative' }}>
          <Context实例演示12_2 text={'13_1hoc高阶组件案例1__withFloatBtn'} />
        </View>

        <MemoAndUsememo />

        <Divide isBig />
        <RefDemo />

        <Divide isBig />
        <CommunicateWithNative />
      </ScrollView>
      {/* ------------------------------------------------------ */}
      <Divide isBig>
        <Text>需要另外一个页面</Text>
      </Divide>
      {/* <ScrollViewDemo7_12 />
      <FlatListDemo7_13 />
      <SectionList7_14 />*/}
      {/* <ModalDemo7_16 /> */}
      {/* <跟随动画延迟难题9_10 />
      <自定义Modal背景动画910_from_ModalDemo7_16 />*/}

      {/* <ConsumeList14_2 /> */}

      {/*TODO:暂时没有搞定 webView */}
      {/* <MyWeb /> */}
      {/* <MyInlineWeb /> */}
    </SafeAreaView>
  )
}

const styles = StyleSheet.create({
  sectionContainer: {
    marginTop: 32,
    paddingHorizontal: 24
  },
  sectionTitle: {
    fontSize: 24,
    fontWeight: '600'
  },
  sectionDescription: {
    marginTop: 8,
    fontSize: 18,
    fontWeight: '400'
  },
  highlight: {
    fontWeight: '700'
  },
})

class MyWeb extends Component {
  render() {
    return (
      <WebView
        originWhitelist={['*']}
        source={{ uri: 'https://infinite.red' }}
        style={{
          backgroundColor: '#f1f1f180',
          position: 'absolute',
          top: 20,
          bottom: 0,
          left: 0,
          right: 0
        }}
      />
    )
  }
}

class MyInlineWeb extends Component {
  render() {
    return (
      <></>
      // <WebView
      //   originWhitelist={['*']}
      //   source={{html: '<h1>Hello world</h1>'}}
      //   style={{
      //     position: 'absolute',
      //     top: 20,
      //     bottom: 0,
      //     left: 0,
      //     backgroundColor: '#f1f1f180',
      //     right: 0
      //   }}
      // />
    )
  }
}
// root
function root() {
  return (
    <ScrollProvider>
      <App />
    </ScrollProvider>
  )
}

export default root
